package com.study.es;

import com.study.es.dao.ProductDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataESProductSearch {
    @Resource
    private ProductDao productDao;

    /**
     * term查询
     * */
    @Test
    public void termSearch(){
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
        this.productDao.search(termQueryBuilder).forEach(System.out::println);
    }

    /**
     * term查询加分页
     * */
    @Test
    public void termSearchPage(){
        int currentPage=0;
        int sizePage=5;
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
        PageRequest pageRequest=PageRequest.of(currentPage,sizePage);
        this.productDao.search(termQueryBuilder,pageRequest).getContent().forEach(System.out::println);
    }

    /**
     * 查询加分页加排序
     * */
    @Test
    public void searchOrderPage(){
        int currentPage=0;
        int sizePage=5;
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
        NativeSearchQuery nativeSearchQuery=new NativeSearchQuery(termQueryBuilder);
        PageRequest pageRequest = PageRequest.of(currentPage, sizePage);
        nativeSearchQuery.setPageable(pageRequest);
        List<String> list=new ArrayList<>();
        list.add("id");
        Sort sort=Sort.by(Sort.Order.desc("id"));
        nativeSearchQuery.addSort(sort);
        this.productDao.search(nativeSearchQuery).getContent().forEach(System.out::println);
    }

    /**
     * 查询分页以及排序
     * */
    @Test
    public void searchOrderPages(){
        int currentPage=0;
        int sizePage=5;
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "5小米手机");
        Sort sort=Sort.by(Sort.Direction.DESC,"id");
        PageRequest pageRequest = PageRequest.of(currentPage, sizePage, sort);
        this.productDao.search(termQueryBuilder,pageRequest).getContent().forEach(System.out::println);
    }


}
